<template>
  <div class="sop_list table-theme">
    <head-title title="公众号--SOP列表"></head-title>
    <el-card>
      <div class="top-menu">
        <div class="menu-left">
        </div>
        <div class="menu-right">
          <refresh-button @refresh="refreshPage"></refresh-button>
          <div class="add">
            <el-button type="primary" @click="add('one')"
              >添加第一级SOP</el-button
            >
          </div>
        </div>
      </div>
      <p class="data-number">总列表数：{{ total }}</p>
      <el-table :data="list" stripe border :tree-props="{children:'children'}" row-key="gzh_sop_id">
        <el-table-column
          label="序号"
          align="center"
          width="140"
          prop="gzh_sop_id"
        >
        </el-table-column>
        <el-table-column label="上级ID" align="center" width="140">
          <template slot-scope="scope">
            {{ scope.row.parent_id ? scope.row.parent_id : "无" }}
          </template>
        </el-table-column>
        <el-table-column
          label="提问"
          align="center"
          prop="ask"
        ></el-table-column>
        <el-table-column
          label="答案"
          align="center"
          prop="answer"
        ></el-table-column>
        <el-table-column
          label="等级"
          align="center"
          prop="level"
          width="140"
        ></el-table-column>
        <el-table-column
          label="时间"
          align="center"
          prop="add_time"
          width="220"
        ></el-table-column>
        <el-table-column
            label="操作"
            align="center"
            
        >
        <template slot-scope="scope">
            <el-button type="primary" size="mini" v-if="scope.row.level<3 && !scope.row.is_add" @click="add('two',scope.row)">新增下级SOP</el-button>
            <el-button type="primary" size="mini" @click="addImg(scope.row.gzh_sop_id)">上传图片</el-button>
            <el-button type="primary" size="mini" @click="onDel(0,scope.row.gzh_sop_id,scope.row)">修改</el-button>
            <el-button type="danger" size="mini" @click="onDel(1,scope.row.gzh_sop_id)">删除</el-button>
        </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加sop弹框 -->
    <el-dialog
      :title="title"
      :visible.sync="addDialog"
      width="500px"
      center
      :modal-append-to-body="false"
      @close="onClose"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addForm"
        label-width="120px"
      >
        <el-form-item label="提问:" prop="ask">
          <el-input
            v-model.trim="addForm.ask"
            placeholder="请输入提问"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="答案:" prop="answer">
          <el-input
          type="textarea"
            v-model.trim="addForm.answer"
            placeholder="请输入答案"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="等级:" prop="level">
          <el-select
            v-model="addForm.level"
            placeholder="请选择等级"
            @change="init(1)"
            :disabled="is_disabled"
          >
            <el-option
              v-for="item in levelLists"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级ID:" prop="parent_id" v-if="addForm.level > 1">
          <el-input
            v-model.trim="addForm.parent_id"
            placeholder="请输入上级ID"
            :disabled="is_disabled"
            clearable
          ></el-input>
        </el-form-item>
        <p class="hint">温馨提示:上级最多关联8个,填写内容不可有空格!</p>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="onClose">取 消</el-button>
        <el-button type="primary" @click="submit('add','addForm')">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加图片 -->
    <el-dialog
      title="上传图片"
      :visible.sync="is_img"
      width="500px"
      center
      :modal-append-to-body="false"
    >
      <el-form
        :model="addImgForm"
        :rules="addImgFormRules"
        ref="addImgForm"
        label-width="120px"
      >
        <el-form-item label="图片:" prop="file">
          <div class="headImg">
							<el-upload class="avatar-uploader" ref="upload" action="fakeaction" :show-file-list="false" 
              :http-request=" function(res) { return upload(res); } "
							 multipleaccept="image/*" :on-change="onchange"> <img v-if="imageUrl" :src="imageUrl" class="avatar" />
								<i v-else class="el-icon-plus avatar-uploader-icon"></i>
							</el-upload>
						</div>
        </el-form-item>
        <p class="hint">温馨提示:图片不能大于1M!</p>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="onImgClose">取 消</el-button>
        <el-button type="primary" @click="submit('img','addImgForm')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      page: 1,
      total: 0,
      list: [],
      asc: 1,
      order_by: "add_time",
      level: "",
      addDialog: false,
      addForm: {
        ask: "",
        answer: "",
        level: "",
        parent_id: "",
      },
      levelLists: [
        {
          value: 1,
          label: "一",
        },
        {
          value: 2,
          label: "二",
        },
        {
          value: 3,
          label: "三",
        },
      ],
      addFormRules: {
        ask: [{ required: true, message: "必填项不能为空" }],
        answer: [{ required: true, message: "必填项不能为空" }],
        level: [{ required: true, message: "请选择等级" }],
        parent_id: [{ required: true, message: "请填写直属上司ID" }],
      },
      addType:"add",
      title:"添加sop",
      limit:300,
      is_disabled:false,
      img:'',
      gzh_sop_id:'',
      is_img:false,
      addImgForm:{
        file:'',
        type:'image',
        gzh_sop_id:''
      },
      addImgFormRules:{
         file: [{ required: true, message: "请上传图片" }]
      },
      imageUrl:'',
      formData:''
    };
  },
  methods: {
    // 清除搜索内容
    refreshPage() {
      this.page = 1;
      this.type = 0;
      this.asc = 1;
      this.level = "";
      this.order_by = "add_time"
      this.init(1);
    },
    init(e) {
      this.page = e;
      let data = {
        page: e - 1 ? e - 1 : 0,
        limit: this.limit,
        order_by: this.order_by,
        asc: this.asc,
        level: '',
      };
      this.$http(this.$ApiList.SopList, data).then((res) => {
        const { count, data } = res.datas;
        this.total = count;
        let list = [];
        data.forEach(item=>{
          let children = [];
          if(!item.parent_id){
            data.forEach(data=>{
              if(data.parent_id == item.gzh_sop_id){

                children.push(data);
                item.children = children;
              }
            })
            list.push(item);
          }
        })
        list.forEach(a=>{
          if(a.children){
             a.children.forEach(b=>{
              let children = []
              data.forEach(c=>{
                if(b.gzh_sop_id == c.parent_id){
                  children.push(c);
                  b.children = children;
                }
              })
            })
          }
        })
        list.forEach(a=>{
          if(a.children){
            if(a.children.length === 8){
              a.is_add = true;
            }
             a.children.forEach(b=>{
              if(b.children){
                if(b.children.length === 8){
                  b.is_add = true;
                }
              }
            })
          }
        })
        this.list = list;
      });
    },
    // 添加sop
    submit(type,formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if(type === 'add'){
            if (this.addForm.level < 2) {
            delete this.addForm.parent_id;
          }
          if(this.addType == 'add'){
              this.$http(this.$ApiList.AddSop, this.addForm).then((res) => {
                this.$message.success(res.datas);
                this.init(this.page);
                this.onClose();
            });
          }else if(this.addType == 'up'){
              this.$http(this.$ApiList.UpSop,this.addForm).then((res) => {
                this.$message.success(res.datas);
                this.init(this.page);
                this.onClose();
            })
          }
          }else if(type === 'img'){
            this.formData.append('type','image');
            this.formData.append('gzh_sop_id',this.addImgForm.gzh_sop_id);
            this.$http(this.$ApiList.AddImageSop,this.formData).then(res=>{
              this.$message.success('上传成功');
              this.onImgClose();
            })
          }
        }
      });
    },
    // 取消
    onClose(){
        this.addDialog = false;
        this.addForm.ask = "";
        this.addForm.answer = "";
        this.addForm.level = 1;
        this.$set(this.addForm,'parent_id','')
        this.$refs['addForm'].resetFields();
        this.is_disabled = false;
        
    },
    // 删除
    onDel(type,gzh_sop_id,row){
        if(type == 0){
            this.title = '编辑sop';
            this.addDialog = true;
            this.addForm = JSON.parse(JSON.stringify(row));
            this.addType = 'up'
            this.is_disabled = true;
        }else if(type == 1){
            this.$confirm('此操作将删除该数据, 是否继续?','提示',{
            confirmButtonText:'确定',
            cancelButtonText:'取消',
            type:"warning"
          }).then(()=>{
              this.$http(this.$ApiList.DelSop,{gzh_sop_id}).then(res=>{
                  this.$message.success(res.datas);
                  this.init(this.page);
              })
          })
        }
        
    },
    // 添加
    add(type,row){
        this.addDialog = true;
        this.addType = 'add';
        if(type === 'one'){
          this.addForm.level = 1;
          this.title = '添加sop';
        }else if(type === 'two'){
          this.addForm.level = row.level+1;
          this.addForm.parent_id = row.gzh_sop_id;
        }
        this.is_disabled = true;
    },
    addImg(gzh_sop_id){
      this.addImgForm.gzh_sop_id = gzh_sop_id;
      this.is_img = true;
    },
    upload(params){
      const file = params.file,
        isJPGPNG = file.type === 'image/jpeg' || 'image/png',
        isLt1MB = file.size / 1024 <= 1024;
        if(!isJPGPNG){
          this.$message.error('只能上传图片格式png、jpg!');
          this.imageUrl = '';
          return;
        }
        if(!isLt1MB){
          this.$message.error('图片不能大于1M');
          this.imageUrl = '';
          return;
        }
        this.formData = new FormData();
        this.formData.append('file[]',file);
        this.addImgForm.file = file
    },
    onchange(file, fileList) {
			var event = event || window.event;
			var file = event.target.files[0];
			var reader = new FileReader();
			//转base64
			reader.onload = e => {
				this.imageUrl = e.target.result; //将图片路径赋值给src
			};
			reader.readAsDataURL(file);
		},
    onImgClose(){
      this.imageUrl = '';
      this.addImgForm.file ='';
      this.is_img = false;
      this.formData = ''
    }
  },
  mounted() {
    this.init();
  },
};
</script>

<style lang="scss" scoped>
.hint{
  font-size: 14px;
  color: #dc3545;
  text-align: center;
}
.el-select{
  width: 100%;
}
.cell button{
  margin-bottom: 10px;
}
</style>